"""
CLI命令执行模块

提供CLI主程序中各命令的具体执行逻辑。
"""

import logging
from typing import Dict, Any, List
from pathlib import Path

from .backup.backup_executor import BackupExecutor
from .task_scheduler import TaskScheduler
from .config.manager import ConfigManager
from .core import DatabaseBackup
from .config import generate_toml_config, ConfigTemplates


class BackupCommandExecutor:
    """备份命令执行器"""
    
    def __init__(self, logger: logging.Logger):
        """初始化备份命令执行器
        
        参数:
            logger (logging.Logger): 日志记录器
        """
        self.logger = logger
    
    def validate_configs(self, config_manager: ConfigManager) -> int:
        """验证配置文件
        
        参数:
            config_manager (ConfigManager): 配置管理器实例
        
        返回:
            int: 退出代码
        """
        self.logger.info(f"开始验证配置文件目录: {config_manager.get_config_dir()}")
        config_status = config_manager.validate_backup_configs()
        
        success_configs = config_status['success']
        failed_configs = config_status['failed']
        
        total_files = len(success_configs) + len(failed_configs)
        
        if total_files == 0:
            self.logger.error("未找到任何配置文件")
            return 1
        
        self.logger.info(f"找到 {total_files} 个配置文件")
        
        # 显示验证通过的配置文件
        if success_configs:
            self.logger.info(f"验证通过 ({len(success_configs)} 个):")
            for config in success_configs:
                config_file = config.get('_config_file', 'unknown')
                self.logger.info(f"  - {config_file}: 验证通过")
        
        # 显示验证失败的配置文件
        if failed_configs:
            self.logger.info(f"验证失败 ({len(failed_configs)} 个):")
            for config in failed_configs:
                config_file = config.get('_config_file', 'unknown')
                self.logger.info(f"  - {config_file}: 验证失败")
        
        return 0
    
    def execute_backup(self, config_manager: ConfigManager, config_file: str = None) -> int:
        """执行备份操作
        
        参数:
            config_manager (ConfigManager): 配置管理器实例
            config_file (str, optional): 指定配置文件路径
        
        返回:
            int: 退出代码
        """
        # 加载配置文件
        if config_file:
            config_list = config_manager.load_backup_configs_with_validation(config_file)
            if not config_list:
                return 1
            self.logger.info(f"加载指定配置文件: {config_file}")
        else:
            config_list = config_manager.load_backup_configs_with_validation()
            if not config_list:
                return 1
            self.logger.info(f"加载配置目录下所有配置文件")
        
        # 创建备份执行器
        backup_executor = BackupExecutor(self.logger)
        
        # 创建任务调度器
        max_workers = config_manager.get_max_workers()
        scheduler = TaskScheduler(max_workers=max_workers)
        self.logger.info(f"使用最大并发数: {max_workers}")
        
        # 执行备份任务
        summary = scheduler.schedule_tasks(config_list, backup_executor.execute_backup)
        
        if summary['success_rate'] == 100:
            self.logger.info("所有备份任务执行成功")
            return 0
        else:
            self.logger.warning(f"部分备份任务失败，成功率: {summary['success_rate']:.1f}%")
            return 1


class ConfigCommandExecutor:
    """配置命令执行器"""
    
    def __init__(self, logger: logging.Logger):
        """初始化配置命令执行器
        
        参数:
            logger (logging.Logger): 日志记录器
        """
        self.logger = logger
    
    def generate_config_template(self, db_type: str, output_path: str) -> int:
        """生成配置文件模板
        
        参数:
            db_type (str): 数据库类型
            output_path (str): 输出文件路径
        
        返回:
            int: 退出代码
        """
        try:
            # 生成默认配置模板
            template_config = DatabaseBackup.generate_template_config()
            
            # 设置数据库类型
            template_config['type'] = db_type
            
            # 生成TOML配置内容
            toml_content = generate_toml_config(template_config, db_type)
            
            # 写入文件
            output_path_obj = Path(output_path)
            output_path_obj.parent.mkdir(parents=True, exist_ok=True)
            
            with open(output_path_obj, 'w', encoding='utf-8') as f:
                f.write(toml_content)
            
            self.logger.info(f"配置文件模板已生成: {output_path}")
            self.logger.info(f"数据库类型: {db_type}")
            self.logger.info("请根据实际情况修改配置文件中的参数")
            
            return 0
                
        except Exception as e:
            self.logger.error(f"生成配置文件时发生错误: {e}")
            return 1